package com.zto.sch.base.normal.classload;

import java.io.*;
import java.util.HashMap;
import java.util.Map;

/**
 * @program: sch-diy-parent
 * @description:
 * @author: sch
 * @create: 2021-01-09 12:19
 **/
public class MyClassLoaderParentFirst extends ClassLoader {
    private Map<String, String> classPathMap = new HashMap<>();

    public MyClassLoaderParentFirst() {
        classPathMap.put("com.zto.sch.base.normal.classload.TestA", "/Users/sch/mydocument/mystudy/java-EE/core/sch-diy-parent/daily-learn/target/classes/com/zto/sch/base/normal/classload/TestA.class");
        classPathMap.put("com.zto.sch.base.normal.classload.TestB", "/Users/sch/mydocument/mystudy/java-EE/core/sch-diy-parent/daily-learn/target/classes/com/zto/sch/base/normal/classload/TestB.class");
    }

    @Override
    protected Class<?> findClass(String name) throws ClassNotFoundException {
        String classPath = classPathMap.get(name);
        File file = new File(classPath);
        if (!file.exists()) {
            throw new ClassNotFoundException();
        }
        byte[] classBytes = getClassData(file);
        if (classBytes == null || classBytes.length == 0) {
            throw new ClassNotFoundException();
        }
        return defineClass(null, classBytes, 0, classBytes.length);
    }

    private byte[] getClassData(File file) {
        try (InputStream ins = new FileInputStream(file); ByteArrayOutputStream baos = new
                ByteArrayOutputStream()) {
            byte[] buffer = new byte[4096];
            int bytesNumRead = 0;
            while ((bytesNumRead = ins.read(buffer)) != -1) {
                baos.write(buffer, 0, bytesNumRead);
            }
            return baos.toByteArray();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return new byte[]{};
    }
}
